# Create your views here.

from models import *
from django.shortcuts import render_to_response
from django.shortcuts import HttpResponse
from django.template import RequestContext
from django.contrib.auth.forms import PasswordResetForm, PasswordChangeForm
from models import User
from Eventati.App.models import MaybeAttending, NotAttending
import operator
import datetime
from datetime import date
from django.contrib.sessions.backends.db import SessionStore

emailSession = SessionStore()

#This Method used to create a new template.
#Author:Maged El-Zeiny
#def Templates(request):
#These are the lists rendered to be used in the dropdown menus.
 #   Locations=Location.objects.all()
  #  Medias=Media.objects.all()
   # Agendas=Agenda.objects.all()
    #socialMarketings=socialMarketing.objects.all()
    #Payments=Payment.objects.all()
    #if request.method == "POST":
	#getting input from the text field
        #name = request.POST.get('name', '')
		#getting inputs of checkboxes
        #if request.POST.get('hasLocation')=="on":
         #   hasLocation=true
        #else:
         #   hasLocation=false
        #if request.POST.get('hasPayment')=="on":
         #   hasPayment=true
        #else:
         #   hasPayment=false            
        #if request.POST.get('hasMedia')=="on":
         #   hasMedia=true
        #else:
        #    hasMedia=false     
        #if request.POST.get('hasLiveStream')=="on":
         #   hasLiveStream=true
        #else:
         #   hasLiveStream=false
        #if request.POST.get('hasSocialMarketing')=="on":
         #   hasSocialMarketing=true
        #else:
        #    hasSocialMarketing=false
        #if request.POST.get('hasAgenda')=="on":
       #     hasAgenda=true
      #  else:
     #       hasAgenda=false
#getting Inputs of Dropdown Menus.            
        #eventLocation = get_object_or_404(Location, pk=request.POST.get('location_id'))                
        #eventMedia = get_object_or_404(Media, pk=request.POST.get('media_id'))
        #eventAgenda = get_object_or_404(Agenda, pk=request.POST.get('agenda_id'))
        #eventHasSocialMarketing = get_object_or_404(socialMarketing, pk=request.POST.get('socialmarketing_id'))
        #eventPayment = get_object_or_404(Payment, pk=request.POST.get('payment_id'))                
        #Creating the template and saving it to the database.
       # new_template = Template.objects.create(eventPayment=eventPayment,eventLocation=eventLocation,eventMedia=eventMedia,eventAgenda=eventAgenda,eventHasSocialMarketing=eventHasSocialMarketing,,name=name, hasLocation = hasLocation,hasPayment=hasPayment,hasMedia=hasMedia,hasLiveStream=hasLiveStream,hasSocialMarketing=hasSocialMarketing,hasAgenda=hasAgenda)
        #new_template.save()
		#redirecting to list of templates if the template was created.
        #return HttpResponseRedirect("listoftemplates.html")
		#rendering the lists needed for the dropdown menu.
    #return render_to_response ('CTemplate.html', locals(),context_instance=RequestContext(request)) 



def addLiveStream(request):
    return render_to_response("LiveStream.html")

"""addLiveStream Documentation 
    This method is used just to redirect to the page where the event creator enters the information 
    required for LiveStream Component and it is added until code is integrated. 
    Args: The method takes the request coming from opening the page
    Returns:
    method returns LiveStream.html page
    How to use the function:
    Type the localhost "127.0.0.1:8000/addLiveStream/ """

def verifyChannel(request):
    if request.method == "POST":
           link = request.POST.get('channel', '')
           correcturl = "http://www.ustream.tv/channel"
           if link[0:29] == correcturl:
               isCorrect= True
               channelID = link[29:]  
               resource = "http://www.ustream.tv/embed" + channelID
               new_livestream = LiveStream.objects.create(channel=resource)
               return render_to_response("LiveStream.html" , locals())
           else:
               errormsg = "The link entered is incorrect. Please enter the correct link."
               return render_to_response("LiveStream.html", {'errormsg': errormsg})
    else:
        return render_to_response("LiveStream.html", RequestContext(request))        

def addChannel(request):
    if request.method == "POST":
        return viewSuccess(request)
    else:
        return render_to_response("LiveStream.html", RequestContext(request))    

    
""""addChannel Documentation 
this method embeds the link of event creator's uStream.tv channel in the event page
Args: The method takes the request coming from the LiveStream.html page
Returns:
the method returns Event.html where the livestream video is embedded
How to use the function:
When the event creator clicks on the Submit button this method is called"""

def goToSuccess(request):
    return viewSuccess(request)
		
def setSocialMarekting(request):
    if request.method == 'POST':
            facebookUrl = request.POST.get('facebookUrl')
            twitterUrl = request.POST.get('twitterUrl')
            hashTag = request.POST.get('hashTag')
            new_FacebookUrl= SocialMarketing.objects.create(facebookUrl=facebookUrl)
            new_twitterUrl= SocialMarketing.objects.create(twitterUrl=twitterUrl)
            new_twitterHashtag= SocialMarketing.objects.create(hashTag=hashTag)
    return render_to_response("Social.html",RequestContext(request))
#setSocialMarekting documentation
#this method takes as an input the event creator's facebook url or twitter url or hashtag and
#and adds them to the database to help the event creator to communicate with other other users using
#these social networks
#Args: No Args
#returns an html page which requests the user to enter facebook url or twitter url or hashtag 
# How to use this function:
##open localhost:8000/Social/ and enter requested info
 

def pendingEvent(request):
    variables ={"newapp": Event.objects.all()}
    return render_to_response("pending.html", variables)

def approve(request):
    if request.method =='POST':
        pendng_list = request.POST.getlist('pending')
        for e in pendng_list:
            event = Event.objects.get( id = e )
            event.isApproved = True
            event.visibility = True
            event.save()   
    return pendingEvent(request)

def reject(request):
    if request.method =='POST':
        pendng_list = request.POST.getlist('pending')
        for e in pendng_list:
            event = Event.objects.get( id = e )
            event.isRejected = True
            event.save()
       #     Event.objects.get( id = e ).delete()
    return pendingEvent(request)
def deleteEvent(request):
# tempEmail = request.session['email']
# eventID = request.session['Event.id']
    eventID = 11
    tempEmail = 'sherine_nouh@hotmail.com'
    for e in Event.objects.all():
        if(e.creator.email == tempEmail):
             Event.objects.get( id = eventID ).delete()
             return HttpResponse("Event Destroyed MWAHAHAHAHHAHAHAHAHHAHAHA")
        else:
            return HttpResponse("not here lalallala")
        
def systemModerator(request):
    return render_to_response("systemModerator.html")

def home(request):
    return render_to_response("home.html")

    
def createList(request):
    
    if request.method == 'POST':
        listID = request.POST.get('listID', '')
        list = List()
        list.title = listID
        list.save()
        request.session['list'] = list
        return render_to_response("lists.html" ,locals())


def viewList(request):
    list = request.session['list']
    items = Item.objects.filter(todo_list = list)
    return render_to_response("lists.html" , locals())

#def viewList(request):
#This method retrieves the Task list related to the Event.
#
#Args:
#-	There are no attributes given for the method itself 
#
#Returns:
#-	There is no output for the message; however the user is redirected to the Lists.html containing the TODO List. 

   

def Page(request):
    return render_to_response("todo.html" )




def AddTask (request):
    if request.method =='POST':
        taskID = request.POST.get('taskID' , '')
        l = request.session['list']
        newTask = Item.objects.create(title = taskID , todo_list = l )
        newTask.save()
        print newTask.title
        return viewList(request)
    
def deleteTask(request):
	if request.method =='POST':
		items_list = request.POST.getlist('task')
		list = request.session['list']
		for I in items_list:
	    		Item.objects.filter(title = I , todo_list = list ).delete()
	return viewList(request)

# def deleteTask(request):
# This method allows the event creator to edit the Task list by deleting items
# Args:
#  There are no attributes given for the method itself
# However this method is initiated through "POST" which takes from the user:
# A list of checked boxes indicating the items or tasks the event creator wants to delete
# Returns:
# It calls the method (viewList) that views the TODO List that displays the updated TODO List.


	
def CompleteTask(request):
    if request.method =='POST':
        items_list = request.POST.getlist('task')
        l = request.session['list']
        for I in items_list:
            item = Item.objects.get(title = I , todo_list = l )
            item.completed = True
            item.save()
            print item.completed
            
    return viewList(request)
      
    
def logIn(request):
    print emailSession
    users = User.objects.all()
    if request.method=="POST":
        user = User.objects.get(email = request.POST['email'])
        if user.password == request.POST['password']:
                email = request.POST['email']
                emailSession["email"] =  request.POST['email']
                emailSession.save()
                emailSession.set_expiry(0)
                emailSession.save()
            
                print  'sherine_nouh@hotmail.com'
                return showEvent(request)
        else:
                return HttpResponse("Your email and password didnt match")
                
				#def logIn(request):
				
				
				#method logIn allows the user to login to the website by entering both email and password. Then the method checks if the email entered exists in the database   
				
				#Args: the method doesn't take attributes 
				#the user only enters his email and password throught mehod POST
				
				#Returnes: if the email exists the method redirects the user to page invite.html else a massege is displayed "Your email and password didnt match"  
				
				#how to use this method:
				
				
				
				
      
def change(request):
    return render_to_response("PasswordReset.html", locals())
            
def resetPassword(request):
    user = User.objects.get(email = request.POST['email'])
    if user.password == request.POST['oldpassword']:
            new = request.POST['newpassword']
            user.password = new
            user.confirmpassword = new
            user.save()
            return HttpResponse("You have successfully changed your password")
    else:
        return HttpResponse("Your old password is incorrect")  
	
		#def resetPassword(request):
		#reseting the user's password 
		
		#the user enters his/her email , old password and new password then the method checks if the old password matches the user's old passord and if the new password matches with the confirmed one
		
		
		#Args: the method doesn't take attributes 
		#the user only enters email,old password ,new password and confirm password throught mehod POST
		
		#Returnes: if yes the old password matches with the user's password reseted if no a display method appears that the old password doesn't match
		#how to use this method:
		
		
#def viewTemplates(request):
    # The method displays all the available templates from the database of Eventati website to the creator of the event 
#Args	
    #The method takes no input however it uses the post method after the user clicks on create event button to choose a specific template
#Returns
	#The method has no return value however it displays the list of templates for the creator in an html page	
def viewTemplates (request):
    variables= {"templates":Template.objects.all()}
    return render_to_response("ListOfTemplates.html",variables,context_instance=RequestContext(request))	


def addEventComponents(request):
    if request.method == "POST":
        templateName= request.POST.get('name')
        #print(templateName)  
        
        payment=Payment.objects.create(paymentAmount=-1)
        media=Media.objects.create()
        location=Location.objects.create(name="not chosen")
        agenda=Agenda.objects.create(title="not chosen")
        livestream=LiveStream.objects.create(channel="not chosen")
        socialMarketing = SocialMarketing.objects.create()
        
        template= CreatorTemplate.objects.create(name=templateName,payment=payment,location=location,agenda=agenda,media=media, liveStream=livestream, socialMarketing=socialMarketing)
        template.save()
        templateId=template.id
        request.session['templateId']=templateId
        print(templateId)
        
        # Create The Event
        creator = User.objects.get(email=emailSession["email"])
        event=Event.objects.create(template=template,creator=creator,count_share=0)    
        newpagecounter = PageCounter.objects.create(event = event, pageCounter =0)  
        newpagecounter.save()
        event.save()
        eventId=event.id
        request.session["eventId"]=eventId
        
    return render_to_response("Components.html",locals(),context_instance=RequestContext(request))
		
from django.core.mail import send_mail
from django.http import HttpResponseRedirect

def getEvent(request,event_id):
    numberoflikes=LikeEvent.objects.filter(event=event_id).count()
    event=Event.objects.get(id=event_id)
    sharenumber=event.count_share
    return render_to_response('EventShare.html',{'numberoflikes':numberoflikes,'sharenumber':sharenumber},RequestContext(request))

#getEvent Documentation
#This method counts the number of likes and the number of shared event and views the share and like buttons
#Args:
#This method takes the request coming from the page and the event_id of specific event 
#Returns:
#This method returns Html page that contains the share and the like buttons and the number of shares and likes done for specific event
#How to use the function:
#Type the localhost "127.0.0.1:8000/Event/1/" in the URL where one is the event_id 


def shareEvent(request,event_id):
    if request.method== "POST":
        attending_user = Attending.objects.filter(event=event_id)
        maybeAttending_user =  MaybeAttending.objects.filter(event=event_id)
        notAttending_user = NotAttending.objects.filter(event=event_id)
        not_invited_user=User.objects.all() 
        for temp in attending_user: 
            not_invited_user=not_invited_user.exclude(id=temp.user_id)
        for temp in maybeAttending_user: 
            not_invited_user=not_invited_user.exclude(id=temp.user_id)
        for temp in notAttending_user: 
            not_invited_user=not_invited_user.exclude(id=temp.user_id)
        event=Event.objects.get(id=event_id) 
        event.count_share = event.count_share+1 
        event.save() 
        send_mail('Eventati', 'Dear User \n This Event Has Been Shared \n The Link is :- http://localhost:8000/event/', 'eventati.noreply@gmail.com',[u.email for u in not_invited_user], False,'eventati.noreply','TopSoft2012');
        return HttpResponseRedirect('../../')

#shareEvent Documentation
#This method send e-mails to the users that did not know about the event before and incrementing the number of shares by one
#Args:
#This method takes the request coming from the page and the event_id which represents the id of specific event
#Returns:  
#This method returns Html page that contains the share and the like buttons and the number of shares and likes done for specific event
#How to use the function:
#Type the localhost "127.0.0.1:8000/Event/1/share/" in the URL where one is the event_id

    
def likeEvent(request,event,user):
    if request.method== "POST":
        like = LikeEvent(user_id=user, event_id=event)
        like.save()
        return HttpResponseRedirect('../../../') 

#likeEvent Documentation
#This method add to the database the user_id and event_id to the LikeEvent table if the user wants to like this event
#Args:
#This method takes the request coming from the page , the event_id and the user_id 
#Returns:  
#This method returns Html page that contains the share and the like buttons and the number of shares and likes done for specific event
#How to use the function:
#Type the localhost "127.0.0.1:8000/Event/1/like/2/" in the URL where one is the event_id ,where 2 is the user_id



#def submitComponents
# part 2:
    # The method checks the components selected by the creator, creates a new component of this type, adds it to a new creatorTemplate and then 
	# checks if the creator has chosen the location component it redirects him to the location component form else it calls the viewAgenda method
#Args
	# The method takes not input however it uses a post method to determine which component has been checked
#Returns
    # The method has no returns however it redirects the creator to the location page if the location component is selected otherwise agendaview
	# method is called 	
def submitComponents(request):
    templateId=request.session['templateId']
    template=CreatorTemplate.objects.get(pk=templateId)
    request.session['template']=template
    
    if request.method=="POST":
        eventName = request.POST.get('EventName')
        startDate= request.POST.get('StartDate')
        endDate= request.POST.get('EndDate')   
        startTime= request.POST.get('StartTime')
        endTime= request.POST.get('EndTime') 
        eventName = request.POST.get('EventName')
        template.eventName = eventName
        template.startDate = startDate
        template.endDate = endDate
        template.startTime = startTime
        template.endTime = endTime
        template.eventName = eventName
        
        if template.name== "Wedding":
            brideName = request.POST.get('BrideName')
            groomName = request.POST.get('GroomName')
            template.brideName = brideName
            template.groomName = groomName
        
        if template.name== "Engagement":
            birthdayOwner = request.POST.get('BirthdayOwner')
            template.birthdayOwner = birthdayOwner
        
        if template.name== "Birthday":
            singerName = request.POST.get('SingerName')
            template.SingerName = singerName
        
        if template.name== "Charity":
            charityType = request.POST.get('CharityType')
            template.charityType = charityType
        template.save()
            
        selectedComponents= request.POST.getlist('component')
        request.session['selectedComponents']=selectedComponents
        print(selectedComponents)
     
        for item in selectedComponents:
           if(item=="Location"):    
               location= Location(name="to be decided")
               location.save()
               template.location=location
               template.save()
          
      
      #=========================================================================
           if(item=="Payment"):
                 pay=Payment(amount=0) 
                 pay.save()
                 template.payment=pay
                 template.save()
          
           if(item=="Media"):
                  media=Media()
                  media.save()
                  template.media=media
                  template.save()  
                  
           if(item=="Agenda"):
              agenda=Agenda(title="to be decided")
              agenda.save()
              template.agenda=agenda
              template.save()
      #=========================================================================
          
           if(item=="Social Marketing"):
            socialmarketing=SocialMarketing()
            socialmarketing.save()
            template.socialmarketing=socialmarketing
            template.save()
          
           if(item=="Live Stream"):
            livestream=LiveStream(channel="to be decided")
            livestream.save()
            template.livestream=livestream
            template.save()    
      
           for item in selectedComponents:
               if(item=="Location"): 
                   return render_to_response("Location.html",locals(),context_instance=RequestContext(request))     
        
    return viewPayment(request)

# def viewPayment
    #The method checks if the payment component is chosen then it redirects the creator to the payment page else it calls the viewAgenda method
# Args	
	#The method takes not input however it uses a post method to determine which component has been checked
# Returns	
	# The method has no returns however it redirects the creator to the payment page if the payment component is selected otherwise viewAgenda
	# method is called 	
	
def viewPayment(request):
    selectedComponents=request.session['selectedComponents']
    for item in selectedComponents:
     if(item=="Payment"): 
       return render_to_response("Payment.html",locals(),context_instance=RequestContext(request))     
    
    return viewAgenda(request)

# def viewAgenda
    #The method checks if the agenda component is chosen then it redirects the creator to the agenda page else it calls the viewMedia method
# Args	
	#The method takes not input however it uses a post method to determine which component has been checked
# Returns	
	# The method has no returns however it redirects the creator to the agenda page if the agenda component is selected otherwise viewMedia
	# method is called	
	
	
def viewAgenda(request):
    selectedComponents=request.session['selectedComponents']
    for item in selectedComponents:    
     if(item=="Agenda"):
		#CreateAgenda(request) 
        return render_to_response("Agenda.html",locals(),context_instance=RequestContext(request)) 
    return viewMedia(request)

# def viewMedia
    #The method checks if the media component is chosen then it redirects the creator to the media page else it calls the viewSocialMarketing method
# Args	
	#The method takes not input however it uses a post method to determine which component has been checked
# Returns	
	# The method has no returns however it redirects the creator to the media page if the media component is selected otherwise viewSocialMarketing
	# method is called	
	
	
def viewMedia(request):
    
    selectedComponents=request.session['selectedComponents']
    for item in selectedComponents:
        print(item)
        if(item=="Media"): 
            return render_to_response("Media.html",locals(),context_instance=RequestContext(request))
    return viewSocialMarketing(request)
 

 
def assignPayment(request):
    if request.method == "POST":
        payAmount = request.POST.get('paymentAmount')
        deadLine = request.POST.get('deadline')
        
        original_Payment = Payment.objects.create(paymentAmount = payAmount, deadline = deadLine) 
        original_Payment.save()
        
        
    return render_to_response("Payment.html")
    
    #assignPayemnt Documentation 
		#this method allows authorized users to enter the paymeant amount and deadline date of an event
		#Args: no args
		#Returns:
		#the method renders to the same page Payment.html
		#How to use the function:
		#this method is used to retrieve and store payment related information and is later viewed on event's page



# def viewSocialMarketing
    #The method checks if the socialmarketing component is chosen then it redirects the creator to the socialmarketing page else it calls the viewLiveStream method
# Args	
	#The method takes not input however it uses a post method to determine which component has been checked
# Returns	
	# The method has no returns however it redirects the creator to the socialmarketing page if the socialmarketing component is selected otherwise viewLiveStream
	# method is called
def viewSocialMarketing(request):
    selectedComponents=request.session['selectedComponents']
    for item in selectedComponents:
     if(item=="Social Marketing"):
        return render_to_response("social.html",locals(),context_instance=RequestContext(request))
    return viewLiveStream(request)

# def viewLiveStream
    #The method checks if the liveStream component is chosen then it redirects the creator to the livestream page else it calls the viewSuccess method
# Args	
	#The method takes not input however it uses a post method to determine which component has been checked
# Returns	
	# The method has no returns however it redirects the creator to the liveStream page if the liveStream component is selected otherwise viewSuccess
	# method is called	
	
def viewLiveStream(request):
    selectedComponents=request.session['selectedComponents']
    for item in selectedComponents:
      if(item=="Live Stream"):
        return render_to_response("LiveStream.html",locals(),context_instance=RequestContext(request))
    return viewSuccess(request)

#def viewSuccess
	#The method redirects the creator to a page notifying him that he has completed template requitments
# Args	
	#The method takes not input however it uses a post method.
# Returns	
	# The method has no returns however it redirects the creator to the success page to tell him that he has completed needed requirments
def viewSuccess(request ):
 eventId = request.session["eventId"]
 selectedComponents=request.session['selectedComponents']	
 return render_to_response("Success.html",locals(),context_instance=RequestContext(request), )
	
	
def editEvent(request,event_id):
    if request.method == 'POST':
        event = Event.objects.get(id=event_id)
        template = CreatorTemplate.objects.get(id=event.template)
        location = Location.objects.get(id=template.location)
        payment = Payment.objects.get(id=template.payment)
        event.eventName = request.POST.get('name')
        template.StartDate = request.POST.get('StartDate')
        template.EndDate = request.POST.get('EndDate')
        template.StartTime = request.POST.get('StartTime')
        template.EndTime = request.POST.get('EndTime')
        location.name = request.POST.get('location')
        payment.paymentAmount = request.POST.get('paymentAmount')
        payment.deadline = request.POST.get('deadline')
        if request.POST.get('visibility')=="on":
            event.visibility = 0
        else:
            event.visibility = 1
        event.save()
        
        
        #return render_to_response('event.html',RequestContext(request))#################
        
    else:
        event = Event.objects.get(id=event_id)
        template = CreatorTemplate.objects.get(id=event.template)
        location = Location.objects.get(id=template.location)
        payment = Payment.objects.get(id=template.payment)
        return render_to_response('EditEvent.html',{'event':event,'template':template,'location':location, 'payment':payment},RequestContext(request))
    
"""editEvent Documentation
This method only allows the moderator to edit event
Args:
request from the coming page and event_id
Returns:
Redirects To the page Event page iew
How to use the funtion:
#Type the localhost "localhost:8000/eventEdit/1/" """

def suggestComponent(request):
    if request.method == 'POST':
        component = Components(title=request.POST.get('name'),description=request.POST.get('desc'),files=request.POST.get('files'),approved=0,rejected=0) 
        component.save()
        #return render_to_response('Events.html',RequestContext(request))
    else:
        return render_to_response('SuggestComponent.html',RequestContext(request))
"""suggestComponent Documentation
This method only allows the user to suggest component to the admin
Args:
the method takes request coming from the page 
Returns:
Returns page the contains the suggested component to be viewed by the admin 
How to use the funtion:
#Type the localhost "http://localhost:8000/suggestComponent/" """

		
def addPayedAttendees(request):
   # userEmail = request.session['email']
    userEmail = request.POST.get('email' , '')
    u = User.objects.get(email = 'Inas.ahmed@gmail.com')
    eventId = request.session["eventId"]
    event = Event.objects.get(pk = eventId)
   # event = Event.objects.create( eventID =  '2' ,  creator = u)
    #for e in Event.objects.all():
       # if e.EventID == eventID:
    for p in PayedAttendees.objects.all():
           if p.event.id == eventId:
               if p.user == u:
                   return HttpResponse("you already paid the fees for this event")
                    
    PayedAttendees.objects.create(user = u, event= event ) 
    successmsg  = "you have successfully paid fees , thank you :D"
    return render_to_response("AttendeePayment.html" , {'successmsg' : successmsg })
	
#addPayedAttendees Documentation 
#this method enables the attendees to pay for the events they are attending
#Args: no args
#Returns:
#this method create a new payed Attendee and insert it in the data base
#How to use the function:
#the attendees use it when they press on the button pay in the event page      
       
def startPayment (request):
    return render_to_response ("AttendeePayment.html")
# startPayment Documentation
#this method redirect to the payment HTML
#Args: no Args
#Returns:
# redirect to the payment HTML
#How to use the function:
#Type the localhost : "127.0.0.1:8000/Start/"
       

def homePage(request):
    variables = User.objects.all()
    return render_to_response("Login.html", variables)

#def homePage(request):
    #this method redirects to an html page which shows the parameters to login or create account
    #Args:
        # no arguments required as this is the start page
    #Returns:
        # redirection to the html
    #how the function works
        #on typing http:\\localhost/Login/



def hello(request):
    variables = User.objects.all()
    return render_to_response("Invite.html", variables)

#def hello(request):
        #this method calls for the html page where invitations are done
    #Args:
        # no arguments are required
    #Returns:
        # redirection to html page
    #how the function works
        #redirects to the page where the creator can invite people to the event
def signup(request):
    if request.method == "POST" :
        users = User.objects.all()
        fname = request.POST.get('first_name')
        lname = request.POST.get('last_name')
        getEmail = request.POST.get('email')
        pw = request.POST.get('password')
        confirmpw = request.POST.get('confirmpassword')
        phoneNum = request.POST.get('phone') 
        if fname and lname and getEmail and pw and confirmpw and phoneNum:
            if (pw != confirmpw):
                return HttpResponse("Confirm password failed")
            for u in users: 
                if u.email == getEmail:
                    return HttpResponse("Email already exists. Please enter another email")
            else:
                User.objects.create(first_name=fname, last_name=lname, email=getEmail, password=pw, confirmpassword=confirmpw, phone=phoneNum)
                return render_to_response("Login.html", locals())
        else:
            return HttpResponse("Please enter all fields")
    else:
        return render_to_response("HomePage.html", RequestContext(request))
    
    #def signup(request):
    #the method creates a new account for the user, he provides his information including first name
    #last name, email, password, password confirmation and phone number. it validates the password entered
    #and checks that the email has not been used before then adds him to users
    #Args:
        # arguments are taken from method POST
    #Returns: 
        #shows an alert if the password and password confirmation fields do not match
        #shows an alert if the email already exists
        #shows an alert if there's one or more missing fields
        #redirects to the login page if sign up successfully
        #if sign up not successfull redirects to the homepage.html
    #how the function works:
        #the method is called upon clicking on create account button in the Login page
    #exceptions:    
       # an error message is shown if the email was already created
       
 def joinEvent(request, event_id):  
 if request.method=="POST":
        attending = Attending.objects.all()
        maybeAttending = MaybeAttending.objects.all()
        notAttending = NotAttending.objects.all()
        getEvent = Event.objects.get(id=event_id)
        uemail = emailSession['email']
        events = Event.objects.all()
        users = User.objects.all()
        invited = Invited.objects.all()
        getUser = User.objects.get(email=uemail)
        if getEvent.isPublic != True:
            for i in invited:
                if i.user.email == uemail and i.event.id == event_id:
                    for a in attending:
                        if a.user.email==uemail and a.event.id==event_id:
                            return HttpResponse("Already responded")
                    for m in maybeAttending:
                        if m.user.email==uemail and m.event.id==event_id:
                            return HttpResponse("Already responded")
                    for n in notAttending:
                        if n.user.email==uemail and n.event.id==event_id:
                            return HttpResponse("Already responded")
                    Attending.objects.create(user=getUser, event=getEvent)
                    return render_to_response("Respond.html", locals())
                    print Attending.objects.get(id=1).user.email
        else:
            for e in events:
                if e.id==event_id:
                    for a in attending:
                        if a.user.email==uemail and a.event.id==event_id:
                            return HttpResponse("Already responded")
                    for m in maybeAttending:
                        if m.user.email==uemail and m.event.id==event_id:
                            return HttpResponse("Already responded")
                    for n in notAttending:
                        if n.user.email==uemail and n.event.id==event_id:
                            return HttpResponse("Already responded")
                    Attending.objects.create(user=getUser, event=getEvent)
                    return render_to_response("Respond.html", locals())
                    print Attending.objects.get(id=1).user.email
            
    else: 
        return HttpResponse("Failed")
    
#def joinEvent(request, event_id):
    #this method adds the user into the attending list of the event only if it is a private event and he is
    #invited or if it is a public event 
    #Args:
        # arguments for this method are taken from the method POST
    #Return:
        # redirects to respond.html to prove successful joining
    #how the function works:
        #the method is called upon clicking on the attending button which is viewed in the event page
    #exceptions:
        # return Failed if both conditions are not satisfied
    

        
    
def maybeAttend(request, event_id):
    if request.method=="POST":
        attending = Attending.objects.all()
        maybeAttending = MaybeAttending.objects.all()
        notAttending = NotAttending.objects.all()
        getEvent = Event.objects.get(id=event_id)
        uemail = emailSession['email']
        events = Event.objects.all()
        users = User.objects.all()
        invited = Invited.objects.all()
        getUser = User.objects.get(email=uemail)
        if getEvent.isPublic != True:
            for i in invited:
                if i.user.email == uemail and i.event.id == event_id:
                    for a in attending:
                        if a.user.email==uemail and a.event.id==event_id:
                            return HttpResponse("Already responded")
                    for m in maybeAttending:
                        if m.user.email==uemail and m.event.id==event_id:
                            return HttpResponse("Already responded")
                    for n in notAttending:
                        if n.user.email==uemail and n.event.id==event_id:
                            return HttpResponse("Already responded")
                    MaybeAttending.objects.create(user=getUser, event=getEvent)
                    return render_to_response("Respond.html", locals())
                    print MaybeAttending.objects.get(id=1).user.email
        else:
            for e in events:
                if e.id==event_id:
                    for a in attending:
                        if a.user.email==uemail and a.event.id==event_id:
                            return HttpResponse("Already responded")
                    for m in maybeAttending:
                        if m.user.email==uemail and m.event.id==event_id:
                            return HttpResponse("Already responded")
                    for n in notAttending:
                        if n.user.email==uemail and n.event.id==event_id:
                            return HttpResponse("Already responded")
                    MaybeAttending.objects.create(user=getUser, event=getEvent)
                    return render_to_response("Respond.html", locals())
                    print MaybeAttending.objects.get(id=1).user.email
            
    else: 
        return HttpResponse("Failed")
    
#def maybeAttend(request, event_id):
    #this method adds the user into the maybe attending list of the event only if it is a private event and he is
    #invited or if it is a public event 
    #Args:
        # arguments for this method are taken from the method POST
    #Return:
        # redirects to respond.html to prove successful joining
    #how the function works:
        #the method is called upon clicking on the maybe attending button which is viewed in the event page
    #exceptions:
        # return Failed if both conditions are not satisfied
        # returns already responded if the user has already responded to this event before

  
    
def notAttend (request, event_id):
     if request.method=="POST":
        attending = Attending.objects.all()
        maybeAttending = MaybeAttending.objects.all()
        notAttending = NotAttending.objects.all()
        getEvent = Event.objects.get(id=event_id)
        uemail = emailSession['email']
        events = Event.objects.all()
        users = User.objects.all()
        invited = Invited.objects.all()
        getUser = User.objects.get(email=uemail)
        if getEvent.isPublic != True:
            for i in invited:
                if i.user.email == uemail and i.event.id == event_id:
                    for a in attending:
                        if a.user.email==uemail and a.event.id==event_id:
                            return HttpResponse("Already responded")
                    for m in maybeAttending:
                        if m.user.email==uemail and m.event.id==event_id:
                            return HttpResponse("Already responded")
                    for n in notAttending:
                        if n.user.email==uemail and n.event.id==event_id:
                            return HttpResponse("Already responded")
                    NotAttending.objects.create(user=getUser, event=getEvent)
                    return render_to_response("Respond.html", locals())
        else:
            for e in events:
                if e.id==event_id:
                    for a in attending:
                        if a.user.email==uemail and a.event.id==event_id:
                            return HttpResponse("Already responded")
                    for m in maybeAttending:
                        if m.user.email==uemail and m.event.id==event_id:
                            return HttpResponse("Already responded")
                    for n in notAttending:
                        if n.user.email==uemail and n.event.id==event_id:
                            return HttpResponse("Already responded")
                    NotAttending.objects.create(user=getUser, event=getEvent)
                    return render_to_response("Respond.html", locals())
                    print NotAttending.objects.get(id=1).user.email
    else: 
        return HttpResponse("Failed")
        
#def notAttend (request, event_id):
    #this method adds the user into the not attending list of the event only if it is a private event and he is
    #invited or if it is a public event 
    #Args:
        # arguments for this method are taken from the method POST
    #Return:
        # redirects to respond.html to prove successful joining
    #how the function works:
        #the method is called upon clicking on the not attending button which is viewed in the event page
    #exceptions:
        # return Failed if both conditions are not satisfied
         # returns already responded if the user has already responded to this event before
def sendInvitation(request):
    render_to_response("Invite.html", locals())   
# def sendInvitation(request):
#this method redirects to an html page where the creator of the event can invite people to this event
 #Args:
        # no arguments are required
    #Returns:
        # redirection to html page
    #how the function works
        #redirects to the page where the creator can invite people to the event
        
def invite(request, event_id):
    if request.method== "POST":
        invited = Invited.objects.all()
        usersList = []
        uEmail = emailSession['email']
        print uEmail
        getEvent = Event.objects.get(id = event_id)
        if getEvent.creator.email==uEmail: 
            invitedList = request.POST.getlist('invite')      
            for i in invitedList:
                getUser = User.objects.get(email=i)
                for inv in invited:
                    if inv.user==getUser and inv.event==getEvent:
                        return HttpResponse("Already invited")
            newInvited = Invited.objects.create(user=getUser, event=getEvent)
            newInvited.save()
                #print Invited.objects.get(id=1).user.email
            return render_to_response("AddToEvent.html", locals())
        else:
            return HttpResponse("You are not authorized to invite people to this event")
    else:
        return HttpResponse("Failed")  
#def invite(request, event_id):
    #this method views all users list where the creator can invite other users 
    #Arguments:
        # this method takes it arguments from the method POST
    #Return:
        # redirects to the welcome page showing successful invitation
    #how the function works:
        #there will be an invite button after creating the event. this function will be called upon cicking on the invite button
    #exceptions:
       #if he is not the creator then a message will be shown to let him know he is not authorized to invite users
# returns Already invited if the creator tries to invite a user who is already invited

  

  
        
def view_attend(request):
    attend = [ ]
    for u in Attending.objects.all():
        attend.append(u)
    return render_to_response('statistics.html', locals())
def view_maybe(request):
    maybe = [ ]
    for m in MaybeAttending.objects.all():
        maybe.append(m)
    return render_to_response('statistics.html', locals())
def view_notAttending(request):
    notattend = [ ]
    for n in NotAttending.objects.all():
        notattend.append(n)
    return render_to_response('statistics.html', locals())
def view_payedAttendees(request):
    pay = [ ]
    for p in PayedAttendees.objects.all():
        pay.append(p)
    return render_to_response('statistics.html', locals())

def viewPage (request):
    return render_to_response('ViewPage.html' , RequestContext(request))
""" The method views a Page with 2 buttons
    Arguments: Request of the page
    Returns: Html page with 2 buttons (1st:view terms and conditions, 2nd:view News)
    Usage: Clicking (view terms&conditions):views the terms&conditions
            Clicking (view Latest News): views the latest news
    """

def viewTerms (request):
     terms = TermsAndCondition.objects.all()
     return render_to_response("Terms&Conditions.html", locals())
""" The method views the terms and conditions Page  
    Arguments: Request of the page
    Returns: html page with the terms and conditions of Eventati. 
    Usage: Viewing the terms page 
    """	

def viewNews (request):
     news = NewAndUpdate.objects.all()
     return render_to_response("News.html", locals())
""" The method views the news Page  
    Arguments: Request of the page
    Returns: html page with the latest news of Eventati. 
    Usage: Viewing the news page 
    """ 

def viewAboutUs(request):
    page_about=AboutUs.objects.all()
    return render_to_response('AboutUs.html' ,locals())

#This method allows the user to view eventati's aboutus page
     #   arguments: request for page
     #   returns: aboutus html page
      #  using the function: Type the localhost : "127.0.0.1:8000/AboutUs/"
#
def viewFaqs(request):
    Faqs=Faq.objects.all()
    return render_to_response('Faqs.html' ,{ 'Faqs': Faqs})

    # This method views the faqs page
    #arguments: request for html page 
    #returns: faqs html page
    #using the function:  Type "127.0.0.1:8000/Faqs/"
 
def viewContactUs(request):
    return render_to_response('Contactus.html' ,RequestContext(request))

     #This method views the contactus page
    #arguments: request for html page 
    #returns: contactus html page
    #using the function:  Type "127.0.0.1:8000/Contactus/"
    
def viewEventati(request):
    return render_to_response('Eventati.html' , RequestContext(request))
    """ This method views a page containing buttons for aboutus, faqs, contactus
        arguments:request for html page
        returns: page containing buttons
        using the function: Type "127.0.0.1:8000/Eventati/"
  
   """	

        
	 

def LaunchEvent(request):
    return render_to_response("MyEvent.html", locals(), context_instance=RequestContext(request))


#The Edit Components Methods 
def editLocation(request):
    event = request.session["event"]
    userEmail = emailSession["email"]
    for e in Event.objects.all():
        if e == event:
            if userEmail == event.creator.email:
                oldLocation = e.CreatorTemplate.location.name
                if request.method=="POST":
                    updatedPlace = request.POST.get('UpdatedPlace')
                    e.template.location.name = updatedPlace  
                    e.save()    
    return render_to_response("Event.html",locals())

def editPaymentAndDeadline(request, id):
    if request.method == "POST":
        editP = request.POST.get('editPayment')
        editD = request.POST.get('editDeadline')
        payAmount = request.POST.get('paymentAmount')
        deadLine = request.POST.get('deadline')
        
        userEmail = request.session['useremail']
        
        for event in Event.objects.all():
            if event.id == id:
               if event.creator.email == userEmail: #for session 
                  event.template.payment.paymentAmount = 'editPayment'
                  event.template.payment.deadline = 'editDeadline'
            
    return render_to_response("EditPayment.html") # to be rendered to event page
    
    #editPaymentAndDeadline Documentation 
		#this method edits the paymeant amount and deadline date of an event and returns it to the EditPayment html page
		#Args: no args
		#Returns:
		#the method renders to the same page until final integration
		#How to use the function:
		#this method is called when the creator clicks on Edit Payment and Edit Deadline button in edit event page


def editAgenda(request):
    return render_to_response("EditAgenda.html", locals())

def editMedia(request):
    return render_to_response("EditMedia.html", locals())

def editLiveStream(request):
	
	if request.method == "POST":

	     eventID = request.session['eventid']
	     link = request.POST.get('channel', '')

	     if link[0:29] == "http://www.ustream.tv/channel":

	         channelID = link[29:]
	         resource = "http://www.ustream.tv/embed" + channelID
	         #check session and change the event's channel
	         for event in Event.objects.all():
	             if event.id == eventID:
	                 event.template.LiveStream.channel = resource
	         return render_to_response("EditLiveStream.html", {'resource': resource})

	     else:
	         errormsg = "The link entered is incorrect. Please enter the correct link."
	         return render_to_response("EditLiveStream.html", {'errormsg': errormsg})
	else:
	     return render_to_response("EditLiveStream.html", RequestContext(request))

"""editLiveStream Documentation 
this method edits the link of event creator's uStream.tv channel and embeds the new channel in the event page
Args: The method takes the request coming from Edit Components page
Returns:
the method returns the same page until code is integrated
How to use the function:
this method is called when the creator clicks on Edit LiveStream button in edit event page"""
        
def editSocialMarketing(request):
    return render_to_response("EditSocialMarketing.html", locals())

def createEvent(request):
  #  if(request.session['email']):
   #     userEmail = request.session['email']
     #   eventId1 = request.session['id']
    #    userEmail1 = User.objects.get(email=userEmail)
     #   event = Event.objects.get(eventID=eventId1)
     #   event.creator.objects.create(userEmail1)
        return render_to_response("CreateEvent.html",locals(),context_instance = RequestContext(request))
   # else:
    #    return HttpResponse("You cannot create an event when you are not logged in!!")
#def createEvent(request):
#this method enables the user to create an event.
#Args: It takes a request from the page.
#Returns: 
#It returns to the template page
#How to use the function:
#Type "127.0.0.1:8000/createEvent/" 
def addMedia(request):
    return render_to_response("Media.html")

def uploadPhoto(request):
    
    if request.method == "POST":
        
        photo = request.POST.get('photo', '')
    
        newPhoto = Media.objects.create(photo=photo)
        
        return render_to_response("MediaTest.html", {'photo':photo})
    else:
        return render_to_response("Media.html", RequestContext(request))
		
		
def uploadVideo(request):
    
    if request.method == "POST":
        
        video = request.POST.get('video', '')
    
        new_video = Media.objects.create(video=video)
        
        return render_to_response("MediaTest.html", {'video':video})
    else:
        return render_to_response("Media.html", RequestContext(request))

def createPage(request):
    return render_to_response("CreatePage.html",RequestContext(request))
#def createPage(request):
#this method redirects to the page where the event creator creats static pages
#arguments : no arguments
#Returns: 
#the redirect to the createPage.html
#How to use the function:
#Type the localhost "localhost:8000/CreatePage/" 

def createRequest (request):
    return render_to_response("Create.html",RequestContext(request))
#def createRequest(request):
#this method redirects to the page where the event creator could create a menu or page
#arguments : no arguments
#Returns: 
#the redirect to the Create.html
#How to use the function:
#Type the localhost "localhost:8000/Create/" 	
	
def addCMS(request):
   
    if request.method == "POST":
        title = request.POST.get('title', '')
        description = request.POST.get('description','')
        category = request.POST.get('Category','')
        newCategory = Category.objects.create(category_title = category)
        newPage = Pages.objects.create(title=title, description = description, category = newCategory)
        print request.method == "POST"
        print newPage.title
        return checkEvents(request)
    else:
        return render_to_response("CreatePage.html", RequestContext(request))
#def addCMS(request):
#this method takes the attributes of the page and create a page for the event creator then redirects the event creator to the event page
#Args : no arguments
#Returns: 
#it returns the pages
#How to use the function:
#Type the localhost "localhost:8000/CreatePage/" 	
        
def createMenus(request):
    if request.method == "POST":
        title = request.POST.get('title', '')
        link = request.POST.get('link','')
        new_link = Link.objects.create(url = link)
        new_Menu = Menu.objects.create(title=title, link = new_link)
        print new_Menu.title
        return checkEvents(request)
    else:
        return render_to_response("CreateMenu.html", RequestContext(request))
#def createMenus(request):
#this method takes the attributes of the menu and create a menu for the event creator then redirects the event creator to the event page
#Args : no arguments
#Returns: 
#it returns to the event page
#How to use the function:
#Type the localhost "localhost:8000/CreateMenu/" 
def checkEvents(request):
    page = Pages.objects.all()
    menus = Menu.objects.all()
    categories = Category.objects.all()
    #ctegories = Menu.objects.all()
    return render_to_response("EventsTest.html", locals()) 
	
#def checkEvents(request):
#this method views all the created pages, menus and categories
#Args : no arguments
#Returns: 
#it returns to the event page
#How to use the function:
#Type the localhost "localhost:8000/EventsTest/" 

def showPages (request,id):
    page = Pages.objects.get(pk = id)
    return render_to_response('ViewCMSPage.html',locals())
#def showPages(request):
#this method views the created page of the user with its content
#Args : no arguments
#Returns: 
#it returns the page the creator created
#How to use the function:
#Type the localhost "localhost:8000/ViewCMSPage/" 
def showMenus (request,id):
    menu = Menu.objects.get(pk = id)
    return render_to_response('Menus.html',locals())
#def showMenus(request):
#this method views the created menu of the user with its content
#Args : no arguments
#Returns: 
#it returns the menu the creator created
#How to use the function:
#Type the localhost "localhost:8000/Menus/" 
    
    		
		
def launchEvent(request):
    selectedComponents=request.session['selectedComponents']    
    return render_to_response("Launch.html",locals(),context_instance=RequestContext(request))
#def launchEvent(request):
#this method enables the user to be able to see buttons that will remove any component he wants.
#Args: It takes a request from the page.
#Returns: 
#It returns to a page saying that this component has been removed
#How to use the function:
#Type "127.0.0.1:8000/launch/" 
       
def removeLocation(request):
    selectedComponents=request.session['selectedComponents']
    if request.method == "POST":
        for item in selectedComponents:       
            if(item=="Location"):
                selectedComponents.remove(item)
                print(selectedComponents)
                return render_to_response("RemovedLocation.html",locals(),context_instance=RequestContext(request))
#def removeLocation(request):
#this method enables the user to remove the Location component after its been added to his event page.
#Args: It takes a request from the page.
#Returns: 
#It returns to a page saying that this component has been removed
#How to use the function:
#Type "127.0.0.1:8000/launch/"                           
def removePayment(request):
    selectedComponents=request.session['selectedComponents']
    if request.method == "POST":
        for item in selectedComponents:       
            if(item=="Payment"):
                selectedComponents.remove(item)
                print(selectedComponents)
                return render_to_response("RemovedPayment.html",locals(),context_instance=RequestContext(request))

#def removePayment(request):
#this method enables the user to remove the Payment Component after its been added to his event page.
#Args: It takes a request from the page.
#Returns: 
#It returns to a page saying that this component has been removed
#How to use the function:
#Type "127.0.0.1:8000/launch/" 
                
def removeMedia(request):
    selectedComponents=request.session['selectedComponents']
    if request.method == "POST":
        for item in selectedComponents:       
            if(item=="Media"):
                selectedComponents.remove(item)
                print(selectedComponents)
                return render_to_response("RemovedMedia.html",locals(),context_instance=RequestContext(request))

#def removeMedia(request):
#this method enables the user to remove the Media Component after its been added to his event page.
#Args: It takes a request from the page.
#Returns: 
#It returns to a page saying that this component has been removed
#How to use the function:
#Type "127.0.0.1:8000/launch/" 
                           
                           
def removeAgenda(request):
    selectedComponents=request.session['selectedComponents']
    if request.method == "POST":
        for item in selectedComponents:       
            if(item=="Agenda"):
                selectedComponents.remove(item)
                print(selectedComponents)
                return render_to_response("RemovedAgenda.html",locals(),context_instance=RequestContext(request))
#def removeAgenda(request):
#this method enables the user to remove the Agenda Component after its been added to his event page.
#Args: It takes a request from the page.
#Returns: 
#It returns to a page saying that this component has been removed
#How to use the function:
#Type "127.0.0.1:8000/launch/"   
 
def removeSocialMarketing(request):
    selectedComponents=request.session['selectedComponents']
    if request.method == "POST":
        for item in selectedComponents:       
            if(item=="Social Marketing"):
                selectedComponents.remove(item)
                print(selectedComponents)
                return render_to_response("RemovedSocialMarketing.html",locals(),context_instance=RequestContext(request))
#def removeSocialMarketing(request):
#this method enables the user to remove the Social Marketing Component after its been added to his event page.
#Args: It takes a request from the page.
#Returns: 
#It returns to a page saying that this component has been removed
#How to use the function:
#Type "127.0.0.1:8000/launch/"           
def removeLiveStream(request):
    selectedComponents=request.session['selectedComponents']
    if request.method == "POST":
        for item in selectedComponents:       
            if(item=="Live Stream"):
                selectedComponents.remove(item)
                print(selectedComponents)
                return render_to_response("RemovedLocation.html",locals(),context_instance=RequestContext(request))      

#def removeLiveStream(request):
#this method enables the user to remove the LiveStream Component after its been added to his event page.
#Args: It takes a request from the page.
#Returns: 
#It returns to a page saying that this component has been removed
#How to use the function:
#Type "127.0.0.1:8000/launch/" 

def templates(request):
    return render_to_response("CreateTemplate.html")

def createTemplate(request):
    if request.method=='POST':
        start = request.POST.get('startID' , '')
        end = request.POST.get('endID' , '')
        template = CreatorTemplate.objects.create(startTime=start, endTime= end )
        template.save()
        request.session['template'] = template
        return render_to_response("Agenda.html")
    else:
        return HttpResponse("Failed")
        
def createAnAgenda (request):  
    if request.method=="POST":
        print "A"
        title = request.POST.get('title' , '') 
        print title
        agendaa =  Agenda()
        agendaa.title = title
        agendaa.save()
        print agendaa
        request.session['agenda'] = agendaa
        creation = "True"
        return render_to_response("Agenda.html", locals())
    else:
        return HttpResponse("Failed")
        
    
def refreshAgenda (request):
        creation = "True"
        agenda =  request.session['agenda'] 
        Activities = Activity.objects.filter(agendaID = agenda)
        return render_to_response("Agenda.html" , locals())

def viewEventAgenda(id):
	event = Event.objects.get(pk = id)
	agenda = event.template.agenda
	activities = Activity.objects.filter(agendaID = agenda) 
	return activities
    
# def viewEventAgenda(id)
# This method retrieves all the activities of an agenda related to a certain event according to its ID
# Args:
# Id (int) : the event's autogenerated ID
# Returns:
# The method returns a list of activities related to the agenda of the event the user wants to see

def createAccount(request):
    return render_to_response('Signup.html', locals())
#def createaccount(request):
# this method calls for the html page where the signup is done
#Args:
#no arguments are required
#Returns:
#redirection to html page
#how the function works
#redirects to the page where the user can signup and create a new account
            
def createActivity(request):
    creation="True"
    if request.method=='POST':
        text = request.POST.get('textID' , '')
        start = request.POST.get('startID' , '')
        end = request.POST.get('endID' , '')
        template = request.session["template"]
        A = request.session['agenda']
    
        if start >= template.startTime and end<=template.endTime:
            new_Activity = Activity()
            new_Activity.description = text
            new_Activity.startTime = start
            new_Activity.endTime = end
            new_Activity.agendaID = A
            new_Activity.save()
            return  refreshAgenda(request)
        else:
            print "Kindly enter valid times"
            return HttpResponse("Kindly go back and enter valid times")
         
    
        
def viewSearchPage(request):
    return render_to_response("Events.html")
#viewSearchPage Documentation
#This method only allows the user to view and uses the Search Engine/Page
#Args:
#Takes no argument
#Returns:
#Redirects To the page Events where the search engine is placed
#How to use the funtion:
#Type the localhost "127.0.0.1:8000" in the URL

def goToPage(request, id):
    idEvent = Event.objects.get(pk=id)
    return viewEvent(request, id)
#goToPage Documentation
#This method is used to direct to a specific Event page when clicked from the results list
#Args:
#The method takes the "id" of the Event page as an argument
#Returns:
#The method returns an HTML page for the specific event page selected
#How to use the funtion:
#Works when an Event is clicked

def searchEngine(request):
    searchCategory = request.POST.get('Categories', '')
    searchKey = request.POST.get('search', '')
    
    if searchCategory =="Name":
        eventsList = []
        for e in Event.objects.filter(isPublic = True):
            if searchKey.lower() in e.eventName.lower():
                eventsList.append(e)
        if not eventsList:
            return HttpResponse ("Sorry, No Results Found")
        else:
            return render_to_response("ResultsEvents.html" , locals())
        
    else:
        if searchCategory =="Location":
            eventsList = []
			for e in Event.objects.filter(isPublic = True):
                if searchKey.lower() in e.eventLocation.lower():
                    eventsList.append(e)
            if not eventsList:
                return HttpResponse ("Sorry, No Results Found")
            else:
                return render_to_response("ResultsEvents.html" , locals())  
        else:
            if searchCategory =="Tag":
                eventsList = []
				for e in Event.objects.filter(isPublic = True):
                    if searchKey.lower() in e.eventTag.lower():
                        eventsList.append(e)
                if not eventsList:
                    return HttpResponse ("Sorry, No Results Found")
                else:
                    return render_to_response("ResultsEvents.html" , locals())
            else:
                if searchCategory =="Category":
                    eventsList = []
					for e in Event.objects.filter(isPublic = True):
                        if searchKey.lower() in e.eventCategory.lower():
                            eventsList.append(e)
                    if not eventsList:
                        return HttpResponse ("Sorry, No Results Found")
                    else:
                        return render_to_response("ResultsEvents.html" , locals())
#searchEngine Documentation
#Search the events table to retrieve a list of events based on a certain search criteria
#Args: 
#No arguments defined
#Returns: 
#HTML page that displays Events' Name, Location, Category, Creator and Visibility
#If no results were found, an Http resonse is returned with a "No results found" Statement
#How to use this function:
#When the Engine is opened, After the user chooses the inputs, on the Search click,
#This method is called to retrieve Results

def viewCounter(id):
    eID = id
    pc = 90
    ev = Event.objects.get(pk = eID)
    page = PageCounter.objects.get(event = ev)
    page.pageCounter = page.pageCounter + 1
    pc = page.pageCounter
    page.save()
    return pc
        

def viewEvent(request , eventId):
    userEmail = 'sherine_nouh@hotmail.com'
    e = Event.objects.get(pk = eventId)
    if e.creator.email == userEmail:
            #author: dalia hegazy
            #this is for viweing the share and like button in the event page 
            user = User.objects.get(email=emailSession['email'])
            numberoflikes=LikeEvent.objects.filter(event=eventId).count()
            sharenumber=e.count_share
            template= e.template
            pageCounter = viewCounter(eventId)
            activities = viewEventAgenda(eventId)
            return render_to_response("CreatorEvent.html",locals(),context_instance=RequestContext(request))
                
        
    else : 
            user = User.objects.get(email=emailSession['email'])
            numberoflikes=LikeEvent.objects.filter(event=eventId).count()
            sharenumber=e.count_share
            template= e.template
            activities = viewEventAgenda(eventId)
            pageCounter = viewCounter(eventId)
            return render_to_response("UserEvent.html",locals(),context_instance=RequestContext(request))

#viewEvent Documentation
#This method allow both creators and users to view the event page but both see it in different views
#Args: 
#Only eventId
#Returns:
#The method redirects To two different HTML pages based on whether the person is a creator or a user of the event and both HTML pages shows the event page requested 
#How to use the function:
#After the template is created and the components are chosen the required information have been entered for each chosen component the creator click on launch event button and CreatorEvent.html appears while if it's a user he/she will just enter the event they want to view id and UserEvent.html will open as well for them

def viewEventAfterLaunch(request):
     eventId = request.session['eventId']
     event=Event.objects.get(pk = eventId)
     template= event.template
     
     return render_to_response("CreatorEvent.html",locals(),context_instance=RequestContext(request))

     


def showEvent (request):
       sessionmail = emailSession['email']
        createdeventsList = []
        attendingeventsList = []

        for e in Event.objects.all():
            if(e.creator.email == sessionmail):
                if(e.date >= date.today()):
                    createdeventsList.append(e)    
                            
        createdeventsList.sort(key=operator.attrgetter('date')) 
        for u in Attending.objects.all():
            if (u.user.email == sessionmail):
                if(u.event.date >=date.today()):
                    attendingeventsList.append(u.event)
    
        attendingeventsList.sort(key=operator.attrgetter('date'))
        return render_to_response('DashboardHome.html', locals())
#def showEvent (request):
    # the method retrieves the most recent upcoming 3 events created and attending and views it in the home page as soon as the user logs in 
    #Args: 
        #no parameters except request as the dashboard is viewed in the home page
    #Returns:
        # a list of events where the user can click on them and he will be directed to the event page
    #how to use the function:
        #in order to test this function open http://localhost/DashBoardHome/  after logging in and creating or attending any event

def showAllCreatedEvents (request):
    allcreatedEvents = []
    sessionmail = 'sherine_nouh@hotmail.com'

    for s in Event.objects.all():
        if(s.creator.email == sessionmail):
            allcreatedEvents.append(s) 
    allcreatedEvents.sort(key=operator.attrgetter('date'))
    return render_to_response('CreatedEvents.html', locals())

#def showAllCreatedEvents (request):
    #the method retrieves a sorted list of all the events that the user created
    #Args:
        # no arguments taken
    #Returns: 
        #redirected to a page with a list of all the events that the user created  where he can click on any event to open its page
    #how to use the function:
        #open http://localhost/DashBoardHome/ after logging in and creating or attending any event 
        #then click the buttin see all
    
def showAllAttendingEvents (request):
    allattendedEvents =[]
    sessionmail = 'sherine_nouh@hotmail.com'
    for e in Attending.objects.all():
        if (e.user.email == sessionmail):
            if(e.event.date >=date.today()):
                allattendedEvents.append(e.event)
    allattendedEvents.sort(key=operator.attrgetter('date'))
    return render_to_response('AttendingEvents.html', locals()) 

#def showAllAttendingEvents (request):
    #the method retrieves a sorted list of all the events that the user will be attending
    #Args:
        # no arguments taken
    #Returns: 
        #redirected to a page with a list of all the events that the user is attending  where he can click on any event to open its page
    #how to use the function:
        #open http://localhost/DashBoardHome/ after logging in and creating or attending any event 
        #then click the buttin see all
    

def showTempEvent (request, id): 
    return  viewEvent(request , id)
    
#def showTempEvent (request, id):  
    #this method only redirects to the event page of the event that the user clicked on
    #Args:
        #takes the event id from the event link upon clicking
    #Returns:
        #redirects to the method viewEvent(request,id) which shows the event page
        #it also passes the event id to it
    #how to use the function:
        # after opening the dashboard http://localhost/DashBoardHome/ click on any of the events that appear
        #u will be directed to the event page through this method

    
  
	
def viewCurrentCredit(request): 
    eventID = request.session['eventId'] 
    event = Event.objects.filter(eventID = eventID)
    paidEvents = PayedAttendees.objects.all()
    count = 0
    for payer in paidEvents:
            if (payer.event.eventID == eventID): 
                count = count+1

    amount =  event.template.payment.paymentAmount 
    credit = amount * count
    return  render_to_response("CurrentCredit.html",  { "credit": credit})

#viewCurrentCredit documentation
#this method calculates the current credit of the eventCreator for a certain event
#Args: no Args
#returns an HTML page containing the Event creator's current credit
# How to use this function:
#the user will open the event page and he will find his current credit displayed
#open #open localhost:8000/CurrentCredit/


def viewInstructions(request):
    Instructions = KnowledgeStore.objects.all()
    return render_to_response("ViewInstructions.html", {"Instructions" : Instructions})
    return render_to_response("ViewInstructions.html")  
def view(request):
    return render_to_response("ViewInstructionions.html")


